import {PageContainer, ProFormText, ProFormTextArea} from '@ant-design/pro-components';
import {Form, message, Card, Space, Button, Alert, Switch} from 'antd';
import React, {useState, useEffect} from 'react';
import {createSwitch, updateSwitch, getSwitchDetails} from '@/services/switch/api';
import {useIntl, useRequest, history, useParams, useLocation} from '@umijs/max';
import {ArrowLeftOutlined} from '@ant-design/icons';
import RuleBuilder from '../components/RuleBuilder';
import ApproverConfig from '../components/ApproverConfig';
import { validateParsedRule, formatValidationErrors, ValidationError } from '@/utils/ruleValidator';
import { switchMetasLike } from '@/services/switch-meta/api';

const CreateUpdatePage: React.FC = () => {
  const intl = useIntl();
  const params = useParams();
  const location = useLocation();
  const [form] = Form.useForm();
  const [messageApi, contextHolder] = message.useMessage();

  // 判断是创建还是编辑
  const isCreate = !params.id;
  const switchId = params.id ? parseInt(params.id as string) : undefined;

  const [initialValues, setInitialValues] = useState<API.SwitchModel | undefined>();
  const [validationErrors, setValidationErrors] = useState<ValidationError[]>([]);
  const [factorOptions, setFactorOptions] = useState<any[]>([]);

  // 获取因子选项数据
  useEffect(() => {
    const fetchFactorOptions = async () => {
      try {
        const response = await switchMetasLike({}, {}, {});
        setFactorOptions(response || []);
      } catch (error) {
        console.error('获取因子选项失败:', error);
      }
    };
    fetchFactorOptions();
  }, []);

  // 编辑模式下渲染开关(基本信息+规则信息+审核信息)
  useEffect(() => {
    if (!isCreate && switchId) {
      const fetchSwitchDetail = async () => {
        try {
          const result = await getSwitchDetails(switchId);
          const switchData = result.data.factor;
          setInitialValues(switchData);

          // 设置表单字段值
          form.setFieldsValue({
            name: switchData.name,
            description: switchData.description,
            useCache: switchData.useCache,
            ruleConfig: switchData.rules,
            createSwitchApproversReq: result.data.approvals
          });
        } catch (error) {
          console.error('获取开关详情失败:', error);
          messageApi.error('获取开关详情失败');
        }
      };
      fetchSwitchDetail();
    }
  }, [isCreate, switchId]);

  const {run, loading} = useRequest(
    (params: API.CreateUpdateSwitchReq) => {
      return isCreate ? createSwitch(params) : updateSwitch(params);
    },
    {
      manual: true,
      onSuccess: () => {
        messageApi.success(isCreate ? '创建成功' : '更新成功');
        // 返回列表页
        history.push('/list/switch');
      },
      onError: () => {
        messageApi.error(isCreate ? '创建失败，请重试' : '更新失败，请重试');
      },
    },
  );

  // 递归解析config字符串为JSON对象
  const parseConfigToJson = (node: any): any => {
    const parsedNode = { ...node };

    // 如果是因子节点，解析config
    if (parsedNode.config && typeof parsedNode.config === 'string') {
      try {
        parsedNode.config = JSON.parse(parsedNode.config);
      } catch (error) {
        // 如果解析失败，保持原值
        console.warn('Config解析失败:', parsedNode.config, error);
      }
    }

    // 递归处理子节点
    if (parsedNode.children) {
      parsedNode.children = parsedNode.children.map((child: any) => parseConfigToJson(child));
    }

    return parsedNode;
  };

  const handleSubmit = async (formValues: any) => {
    // 清除之前的校验错误
    setValidationErrors([]);

    // 规则配置校验
    if (!formValues.ruleConfig) {
      messageApi.error('请配置开关规则');
      return;
    }

    // JSON Schema 校验
    // 拷贝原始数据并解析value从string到json
    const parsedRule = parseConfigToJson(formValues.ruleConfig);
    console.log('解析后的真实JSON:', JSON.stringify(parsedRule, null, 2));

    const validationResult = validateParsedRule(parsedRule, factorOptions);

    if (!validationResult.isValid) {
      setValidationErrors(validationResult.errors);
      const errorMessage = formatValidationErrors(validationResult.errors);
      messageApi.error(`规则配置校验失败：\n${errorMessage}`);
      return;
    }

    // 审批人配置校验
    const approverConfigs = formValues.createSwitchApproversReq || [];
    for (let i = 0; i < approverConfigs.length; i++) {
      const config = approverConfigs[i];
      if (!config.envId) {
        messageApi.error(`第${i + 1}个审批配置的环境不能为空`);
        return;
      }
      if (!config.approverUsers || config.approverUsers.length === 0) {
        messageApi.error(`第${i + 1}个审批配置的审批人不能为空`);
        return;
      }
    }

    // 提交时使用解析后的规则数据
    const params = {...initialValues, ...formValues, rules: parsedRule};
    if (!isCreate && switchId) {
      params.switchId = switchId;
    }
    await run(params);
  };

  const handleReset = () => {
    // 获取当前的开关名称
    const currentName = form.getFieldValue('name');

    form.resetFields();
    form.setFieldsValue({
      name: currentName,
      description: '',
      useCache: false,
      ruleConfig: null,
      createSwitchApproversReq: []
    });
  };

  const handleBack = () => {
    history.push('/list/switch');
  };

  return (
    <PageContainer
      header={{
        title: isCreate ? '新建开关' : '编辑开关',
        breadcrumb: {
          items: [
            {
              path: '/list/switch',
              title: '开关管理',
            },
            {
              title: isCreate ? '新建开关' : '编辑开关',
            },
          ],
        },
        extra: [
          <Button key="back" icon={<ArrowLeftOutlined />} onClick={handleBack}>
            返回列表
          </Button>
        ],
      }}
    >
      {contextHolder}
      <Card>
        <Form
          form={form}
          layout="vertical"
          initialValues={initialValues}
          onFinish={handleSubmit}
          style={{ maxWidth: 1200 }}
        >
          <ProFormText
            name="name"
            label={
              <>
                开关名称
                <span style={{color: '#999', fontSize: '12px', marginLeft: '8px'}}>
                  (创建后不可修改)
                </span>
              </>
            }
            fieldProps={{
              disabled: !isCreate
            }}
            rules={[{required: true, message: '请输入开关名称'}]}
          />

          <ProFormTextArea
            name="description"
            label="开关描述"
            rules={[{required: true, message: '请输入开关描述'}]}
          />

          <Form.Item
            name="useCache"
            label={
              <>
                启用缓存
                <span style={{
                  fontSize: '12px',
                  color: '#faad14',
                  marginLeft: '8px'
                }}>
                  ⚠️ 危险操作，可能导致因子结果错误,非必要请勿打开
                </span>
              </>
            }
            valuePropName="checked"
            initialValue={false}
            style={{ marginTop: '20px' }}
          >
            <Switch
              checkedChildren="开"
              unCheckedChildren="关"
            />
          </Form.Item>

          <div style={{ marginTop: '20px', marginBottom: '20px' }}>
            <Form.Item label="规则配置" name="ruleConfig">
              <RuleBuilder />
            </Form.Item>
          </div>

          {/*{审批方面}*/}
          <ApproverConfig />

          <Form.Item style={{ marginTop: '40px' }}>
            <Space>
              <Button type="primary" htmlType="submit" loading={loading}>
                {isCreate ? '创建' : '更新'}
              </Button>
              <Button onClick={handleReset}>
                重置
              </Button>
              <Button onClick={handleBack}>
                取消
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>
    </PageContainer>
  );
};

export default CreateUpdatePage;
